<template>
  <div>
    <BasicTable @register="registerEntityTable">
      <template #headerTop>
        <Alert v-if="checkedKeys.length > 0" type="info" show-icon class="relative">
          <template #message>
            <div>
              <span>已选中{{ checkedKeys.length }}条记录</span>
              <div class="absolute top-4px right-10px">
                <Tooltip title="分配客户">
                  <a-button type="text" @click="handleSelectedAssign">
                    <Icon :icon="ICON.ASSIGN" color="#0960bd" />
                  </a-button>
                </Tooltip>
                <Tooltip title="删除">
                  <a-button type="text" @click="handleSelectedDelete">
                    <Icon :icon="ICON.DELETE" color="#0960bd" />
                  </a-button>
                </Tooltip>
              </div>
            </div>
          </template>
        </Alert>
      </template>
      <template #toolbar v-if="hasPermission(RoleEnum.TENANT_ADMIN)">
        <a-button type="primary" @click="() => openAddModal(true, { key: 'add' })"
          >添加实体视图</a-button
        >
      </template>
      <template #bodyCell="{ column, record }" v-if="hasPermission(RoleEnum.TENANT_ADMIN)">
        <template v-if="column.key === 'action'">
          <TableAction
            :stopButtonPropagation="true"
            :actions="[
              {
                icon: ICON.EDIT,
                tooltip: {
                  title: '编辑',
                  placement: 'top',
                },
                onClick: openAddModal.bind(null, true, { record, key: 'edit' }),
              },
              {
                icon: ICON.CHECK,
                tooltip: {
                  title: '查看',
                  placement: 'top',
                },
                onClick: handleDetail.bind(null, record),
              },
              {
                icon: ICON.DELETE,
                tooltip: {
                  title: '删除',
                  placement: 'top',
                },
                onClick: handleDelete.bind(null, record),
              },
            ]"
            :dropDownActions="[
              {
                icon: ICON.PUBLIC,
                label: '公开',
                disabled: record.isOpen || record.customerTitle,
                onClick: handlePublic.bind(null, record),
              },
              {
                icon: ICON.ASSIGN,
                label: '分配给客户',
                disabled: record.customerTitle,
                onClick: openCustomerModal.bind(null, true, { record, key: 'customer' }),
              },
              {
                icon: ICON.UNASSIGN,
                label: '取消分配给客户',
                disabled: !record.customerTitle || record.isOpen,
                onClick: handleCancel.bind(null, record),
              },
              {
                icon: ICON.PRIVATE,
                label: '私有',
                disabled: !record.isOpen,
                onClick: handlePrivate.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <PublicDrawer
      @register="registerDrawer"
      @update-desc-data="handleUpdateDescData"
      :show-tabs="
        hasPermission(RoleEnum.CUSTOMER_USER)
          ? ['detail', 'attribute', 'telemetry', 'alarm', 'event', 'association']
          : [
              'detail',
              'attribute',
              'telemetry',
              'alarm',
              'event',
              'association',
              'auditLogs',
              'version',
            ]
      "
    />
    <CustomerModal @register="registerCustomerModal" @success="handleSuccess" />
    <AddEntityModal @register="registerAddModal" @success="handleSuccess" />
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { entityTableSchema, searchSchema, detailSchema } from './entity.data';
  import PublicDrawer from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.vue';
  import { ENTITY_TYPE } from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.data';
  import { useDrawer } from '/@/components/Drawer';
  import { useModal } from '/@/components/Modal';
  import { ICON } from '/@/enums/iconEnum';
  import { useMessage } from '/@/hooks/web/useMessage';
  import AddEntityModal from './modal/AddEntityModal.vue';
  import Icon from '/@/components/Icon';
  import { Alert, Tooltip } from 'ant-design-vue';
  import CustomerModal from './modal/CustomerModal.vue';
  import {
    getEntityViewList,
    addEntityView,
    setViewPublic,
    assignCustomerToView,
    unassignCustomer,
    deleteEntityView,
    getViewInfo,
    getEntityListByCustomerId,
    getEntityListByEdgeId,
    getCustomerEntityViewList,
  } from '/@/api/thingsborad/entity/entity';
  import { addEntityViewParams } from '/@/api/thingsborad/entity/model/entityModel';
  import { useRoute } from 'vue-router';
  import { onMounted } from 'vue';
  import { tableFormStyleSetting, tableStyleSetting } from '/@/settings/thingsBoardDesign';
  import { useUserStore } from '/@/store/modules/user';
  import { RoleEnum } from '/@/enums/roleEnum';
  import { usePermission } from '/@/hooks/web/usePermission';
  const { hasPermission } = usePermission();
  const userStore = useUserStore();
  const checkedKeys = ref<any>([]);
  const [registerEntityTable, { reload, setProps }] = useTable({
    title: '实体视图',
    columns: entityTableSchema,
    ...tableStyleSetting,
    afterFetch: (res) => {
      let list: Recordable[] = [];
      res.length != 0
        ? res.forEach((item: Recordable) => {
            let tableItem: Recordable = {
              createdTime: item.createdTime,
              name: item.name,
              type: item.type,
              customerTitle: item.customerTitle,
              isOpen: item.customerIsPublic,
              id: item.id.id,
            };
            list.push(tableItem);
          })
        : null;
      return list;
    },
    fetchSetting: {
      pageField: 'page',
      sizeField: 'pageSize',
      listField: 'data',
      totalField: 'totalElements',
    },
    actionColumn: hasPermission(RoleEnum.TENANT_ADMIN) ? tableStyleSetting.actionColumn : null,
    formConfig: {
      layout: 'horizontal',
      schemas: searchSchema,
      showAdvancedButton: false,
      ...tableFormStyleSetting,
      actionColOptions: {
        md: { span: 8, offset: 0 },
        lg: { span: 6, offset: 6 },
        xl: { span: 4, offset: 12 },
        xxl: { span: 4, offset: 12 },
      },
      submitFunc: async () => {
        reload();
      },
    },
    rowKey: 'id',
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
    },
  });
  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerCustomerModal, { openModal: openCustomerModal }] = useModal();
  const [registerAddModal, { openModal: openAddModal }] = useModal();
  const { createConfirm } = useMessage();
  // 公开
  function handlePublic(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定要将实体视图 ${record.name} 设为公开吗？`,
      content: '确认后，实体视图及其所有数据将被公开并被他人访问。',
      onOk: async () => {
        await setViewPublic(record.id);
        reload();
      },
    });
  }
  // 私有
  function handlePrivate(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定要将实体视图"${record.entityName}"设为私有吗？`,
      content: '确认后，实体视图及其所有数据将被私有化，无法被他人访问。',
      onOk: async () => {
        await unassignCustomer({ entityType: 'entityView', id: record.id });
        reload();
      },
    });
  }
  // 取消分配
  function handleCancel(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定要取消分配实体视图'${record.name}'吗？`,
      content: '确认后，实体视图将未分配，客户无法访问。',
      onOk: async () => {
        await unassignCustomer({ entityType: 'entityView', id: record.id });
        reload();
      },
    });
  }
  // 删除
  function handleDelete(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定要删除实体视图的"${record.name}"吗？`,
      content: '请注意：确认后实体视图及其所有相关数据将不可恢复。',
      onOk: async () => {
        await deleteEntityView(record.id);
        reload();
      },
    });
  }
  // 详情
  function handleDetail(record: Recordable) {
    openDrawer(true, {
      entityType: ENTITY_TYPE.ENTITY_VIEW,
      entityId: record.id,
      title: record.name,
      api: getViewInfo,
      detailSchema: detailSchema,
      params: record.id,
    });
  }
  // 抽屉详情数据更改
  const handleUpdateDescData = (value: Recordable) => {
    value.name = value.name;
    value.entityViewType = value.type;
    value.description = value.additionalInfo.description;
    value.customer = value.customerTitle;
    value.isOpen = value.customerIsPublic;
    value.clientProperties = value.keys.attributes.cs;
    value.sharedProperty = value.keys.attributes.sh;
    value.serverProperties = value.keys.attributes.ss;
    value.timeseries = value.keys.timeseries;
  };
  // 添加
  const handleAddEntityView = async (values: Recordable) => {
    let params: addEntityViewParams = {
      name: values.entityName,
      type: values.entityViewType,
      entityId: {
        entityType: values.type,
        id: values.type == 'DEVICE' ? values.device : values.asset,
      },
      startTimeMs: null,
      endTimeMs: null,
      keys: {
        attributes: {
          cs: null,
          sh: null,
          ss: null,
        },
        timeseries: null,
      },
      additionalInfo: {
        description: null,
      },
    };
    values.dateRange ? (params.startTimeMs = values.dateRange[0].valueOf()) : null;
    values.dateRange ? (params.endTimeMs = values.dateRange[1].valueOf()) : null;
    values.remark ? (params.additionalInfo.description = values.remark) : null;
    values.clientProperties ? (params.keys.attributes.cs = values.clientProperties) : null;
    values.sharedProperty ? (params.keys.attributes.sh = values.sharedProperty) : null;
    values.serverProperties ? (params.keys.attributes.ss = values.serverProperties) : null;
    values.timeSeries ? (params.keys.timeseries = values.timeSeries) : null;
    await addEntityView(params);
    reload({ sortInfo: { field: 'createdTime', order: 'DESC' } });
  };
  // 编辑
  const handleEditEntityView = async (values: Recordable, viewValues: any) => {
    viewValues.name = values.entityName;
    viewValues.type = values.entityViewType;
    viewValues.entityId.entityType = values.type;
    viewValues.entityId.id = values.type == 'DEVICE' ? values.device : values.asset;
    values.dateRange ? (viewValues.startTimeMs = values.dateRange[0].valueOf()) : null;
    values.dateRange ? (viewValues.endTimeMs = values.dateRange[1].valueOf()) : null;
    viewValues.additionalInfo.description = values.remark;
    values.clientProperties ? (viewValues.keys.attributes.cs = values.clientProperties) : null;
    values.sharedProperty ? (viewValues.keys.attributes.sh = values.sharedProperty) : null;
    values.serverProperties ? (viewValues.keys.attributes.ss = values.serverProperties) : null;
    values.timeSeries ? (viewValues.keys.timeseries = values.timeSeries) : null;
    await addEntityView(viewValues);
    reload();
  };
  const handleCustomer = async (values: Recordable) => {
    let customerParams = {
      customerId: values.customerId,
      entityViewId: values.viewId,
    };
    await assignCustomerToView(customerParams);
    reload();
  };
  // 多选
  function onSelect(record: Recordable, selected: boolean) {
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, record.id];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => id !== record.id);
    }
  }
  // 全选
  function onSelectAll(selected: boolean, _selectedRows: Recordable[], changeRows: Recordable[]) {
    const changeIds = changeRows.map((item) => item.id);
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, ...changeIds];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => {
        return !changeIds.includes(id);
      });
    }
  }
  // 多选分配
  const handleSelectedAssign = () => {
    openCustomerModal(true, { checkedKeys, key: 'selected' });
  };
  // 多选删除
  const handleSelectedDelete = () => {
    createConfirm({
      iconType: 'info',
      title: `确定要删除${checkedKeys.value.length}个实体视图吗？`,
      content: '请注意：确认后，设备及其所有相关数据将不可恢复。',
      onOk: async () => {
        setProps({ loading: true });
        for (const item of checkedKeys.value) {
          await deleteEntityView(item);
        }
        reload();
        checkedKeys.value = [];
      },
    });
  };

  const handleSuccess = async ({ key, values, viewValues }) => {
    switch (key) {
      case 'add':
        handleAddEntityView(values);
        break;
      case 'edit':
        handleEditEntityView(values, viewValues);
        break;
      case 'assign':
        handleCustomer(values);
        break;
      case 'selectedAssign':
        setProps({ loading: true });
        const promises = values.checkedKeys.map((item) =>
          assignCustomerToView({
            customerId: values.customerId,
            entityViewId: item,
          }),
        );
        await Promise.all(promises);
        reload();
        checkedKeys.value = [];
        break;
      case 'assign':
        await assignCustomerToView({
          customerId: values.customerId,
          entityViewId: values.viewId,
        });
        reload();
        break;
    }
  };

  function getParams(val: Recordable) {
    return {
      page: val.page - 1,
      pageSize: val.pageSize,
      sortOrder: val.order == 'ascend' ? 'ASC' : 'DESC',
      sortProperty: val.field,
      textSearch: val.textSearch,
      type: val.type,
    };
  }

  onMounted(async () => {
    const route = useRoute();
    const roleList = userStore.getRoleList;
    const { customerId } = userStore.getUserInfo;
    if (roleList.includes(RoleEnum.TENANT_ADMIN)) {
      if (Boolean(route.params.key)) {
        switch (route.params.key) {
          case '客户':
            setProps({
              api: getEntityListByCustomerId,
              beforeFetch: (val) => {
                return Object.assign(getParams(val), {
                  customerId: route.params.id,
                  infosType: 'entityViewInfos',
                });
              },

              title: `${route.params.name}:实体视图`,
            });
            reload();
            break;
          case '边缘实例':
            setProps({
              api: getEntityListByEdgeId,
              beforeFetch: (val) => {
                return Object.assign(getParams(val), {
                  edgeId: route.params.id,
                  infosType: 'entityViews',
                });
              },
              title: `${route.params.name}:实体视图`,
            });
            reload();
            break;
        }
      } else {
        setProps({
          api: getEntityViewList,
          beforeFetch: (val) => {
            return getParams(val);
          },
        });
        reload();
      }
    } else if (roleList.includes(RoleEnum.CUSTOMER_USER)) {
      setProps({
        api: getCustomerEntityViewList,
        beforeFetch: (val) => {
          return Object.assign({ pagination: getParams(val) }, { customerId: customerId });
        },
      });
      reload();
    }
  });
</script>
